using System;
using System.Linq;
using System.Reflection;

namespace Phoenix.Framework
{
    /// <summary>
    /// Wraps a MethodInfo, making the first argument (if QueryStringArgumentsCollection) transparent
    /// </summary>
    public class MethodDescriptor
    {
        ParameterInfo[] parameters;
        readonly MethodInfo methodInfo;
        bool hasQueryStringArgument;

        public MethodDescriptor(MethodInfo methodInfo)
        {
            this.methodInfo = methodInfo;
        }

        public ParameterInfo[] Parameters
        {
            get
            {
                if (parameters == null)
                {
                    parameters = methodInfo.GetParameters();
                    var firstParam = parameters.FirstOrDefault();
                    if (firstParam != null && firstParam.ParameterType == typeof(QueryStringArgumentsCollection))
                    {
                        parameters = parameters.Skip(1).ToArray();
                        hasQueryStringArgument = true;
                    }
                }

                return parameters;
            }
        }

        public MethodInfo MethodInfo
        {
            get { return methodInfo; }
        }

        public bool HasQueryStringArgument
        {
            get
            {
                //Will cause field to be calculated if it hasn't
                if (Parameters == null)
                    return false;

                return hasQueryStringArgument;
            }
        }
    }
}